<template>
  <div class="maintenance-plan">
    <!-- 维护计划列表 -->
    <div class="header">
      <h2>设备维护计划管理</h2>
      <el-button type="primary" @click="showCreateDialog">新建维护计划</el-button>
    </div>

    <el-table :data="planList" border style="width: 100%">
      <el-table-column prop="planName" label="计划名称" width="180" />
      <el-table-column prop="department" label="所属部门" width="120" />
      <el-table-column prop="deviceType" label="设备类型" width="150" />
      <el-table-column label="维护项目" width="300">
        <template #default="{ row }">
          <div v-for="(item, index) in row.items" :key="index" class="plan-item">
            {{ item.name }}（周期：{{ item.cycle }}天）
          </div>
        </template>
      </el-table-column>
      <el-table-column label="绑定设备" width="200">
        <template #default="{ row }">
          <el-tag v-for="dev in row.boundDevices" :key="dev.id" class="device-tag">
            {{ dev.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="bindDevices(row)">绑定设备</el-button>
          <el-button type="danger" size="small" @click="deletePlan(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建计划对话框 -->
    <el-dialog v-model="createDialogVisible" title="新建维护计划" width="800px">
      <el-form ref="planForm" :model="newPlan" :rules="formRules" label-width="100px">
        <el-form-item label="计划名称" prop="planName">
          <el-input v-model="newPlan.planName" placeholder="请输入计划名称" />
        </el-form-item>

        <el-form-item label="所属部门" prop="department">
          <el-select v-model="newPlan.department" placeholder="请选择部门">
            <el-option
                v-for="dept in departments"
                :key="dept.value"
                :label="dept.label"
                :value="dept.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="newPlan.deviceType" placeholder="请选择设备类型">
            <el-option
                v-for="type in deviceTypes"
                :key="type.value"
                :label="type.label"
                :value="type.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="维护项目" prop="items">
          <div v-for="(item, index) in newPlan.items" :key="index" class="plan-item">
            <el-input
                v-model="item.name"
                placeholder="项目名称"
                style="width: 200px; margin-right: 10px"
            />
            <el-input-number
                v-model="item.cycle"
                :min="1"
                controls-position="right"
                placeholder="周期（天）"
            />
            <el-button
                type="danger"
                circle
                @click="removePlanItem(index)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
          <el-button type="primary" @click="addPlanItem">添加维护项</el-button>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createPlan">确定创建</el-button>
      </template>
    </el-dialog>

    <!-- 设备绑定对话框 -->
    <el-dialog v-model="bindDialogVisible" title="绑定设备" width="60%">
      <el-transfer
          v-model="selectedDevices"
          :data="availableDevices"
          :titles="['可选设备', '已选设备']"
          filterable
      ></el-transfer>

      <template #footer>
        <el-button @click="bindDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveDeviceBinding">确定绑定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'

interface MaintenanceItem {
  name: string
  cycle: number
}

interface MaintenancePlan {
  id: string
  planName: string
  department: string
  deviceType: string
  items: MaintenanceItem[]
  boundDevices: Device[]
}

interface Device {
  id: string
  name: string
  type: string
  department: string
}

// 模拟数据
const deviceList = ref<Device[]>([
  { id: 'D001', name: '空压机-01', type: 'air_compressor', department: 'production' },
  { id: 'D002', name: '数控机床-01', type: 'cnc_machine', department: 'production' },
  { id: 'D003', name: '服务器-01', type: 'server', department: 'it' }
])

const planList = ref<MaintenancePlan[]>([])

// 新建计划相关
const createDialogVisible = ref(false)
const newPlan = reactive({
  planName: '',
  department: '',
  deviceType: '',
  items: [] as MaintenanceItem[]
})

// 绑定设备相关
const bindDialogVisible = ref(false)
const currentPlan = ref<MaintenancePlan | null>(null)
const selectedDevices = ref<string[]>([])

// 选项数据
const departments = [
  { value: 'production', label: '生产部' },
  { value: 'it', label: '信息技术部' },
  { value: 'maintenance', label: '设备部' }
]

const deviceTypes = [
  { value: 'air_compressor', label: '空压机' },
  { value: 'cnc_machine', label: '数控机床' },
  { value: 'server', label: '服务器' }
]

// 表单验证规则
const formRules = {
  planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  department: [{ required: true, message: '请选择部门', trigger: 'change' }],
  deviceType: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  items: [{
    validator: (rule: any, value: any, callback: any) => {
      if (value.length === 0) {
        callback(new Error('至少需要添加一个维护项'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }]
}

// 可用设备计算属性
const availableDevices = computed(() => {
  return deviceList.value
      .filter(dev =>
          dev.type === currentPlan.value?.deviceType &&
          dev.department === currentPlan.value?.department
      )
      .map(dev => ({
        key: dev.id,
        label: dev.name
      }))
})

// 显示创建对话框
const showCreateDialog = () => {
  createDialogVisible.value = true
  newPlan.items = []
}

// 添加维护项
const addPlanItem = () => {
  newPlan.items.push({
    name: '',
    cycle: 7
  })
}

// 删除维护项
const removePlanItem = (index: number) => {
  newPlan.items.splice(index, 1)
}

// 创建计划
const createPlan = () => {
  const newPlanData: MaintenancePlan = {
    id: `MP${Date.now()}`,
    planName: newPlan.planName,
    department: newPlan.department,
    deviceType: newPlan.deviceType,
    items: [...newPlan.items],
    boundDevices: []
  }

  planList.value.push(newPlanData)
  ElMessage.success('维护计划创建成功')
  createDialogVisible.value = false
}

// 绑定设备
const bindDevices = (plan: MaintenancePlan) => {
  currentPlan.value = plan
  selectedDevices.value = plan.boundDevices.map(d => d.id)
  bindDialogVisible.value = true
}

// 保存绑定
const saveDeviceBinding = () => {
  if (!currentPlan.value) return

  currentPlan.value.boundDevices = deviceList.value
      .filter(dev => selectedDevices.value.includes(dev.id))

  ElMessage.success('设备绑定成功')
  bindDialogVisible.value = false
}

// 删除计划
const deletePlan = (plan: MaintenancePlan) => {
  planList.value = planList.value.filter(p => p.id !== plan.id)
  ElMessage.success('计划已删除')
}
</script>

<style scoped>
.maintenance-plan {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.plan-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.device-tag {
  margin: 2px;
}

.el-transfer {
  margin: 0 auto;
}
</style>